#include "Dictionary.h"
#include <cstdio>
#include <cstdlib>

//------------------------------------------------------------------------------

int Dictionary::createToken(const char* text) {
  int ans = getToken(text);
  if (ans == -1) {
    dictmap[text] = ntoken;
    tokenmap[ntoken] = text;
    return ntoken++;
  }
  return ans;
}

//------------------------------------------------------------------------------

int Dictionary::getToken(const char* text) const {
  DictMap::const_iterator it = dictmap.find(text);
  if (it != dictmap.end()) return it->second;
  return -1;
}

//------------------------------------------------------------------------------

const char* Dictionary::getWord(int token) const {
  TokenMap::const_iterator it = tokenmap.find(token);
  if (it != tokenmap.end()) return it->second.c_str();
  fprintf(stderr, "Error: no valid token %d\n", token);
  exit(1);
  return "";
}

//------------------------------------------------------------------------------

void Dictionary::dump() const {
  printf("dict map:\n");
  for (DictMap::const_iterator it = dictmap.begin(); it != dictmap.end(); ++it) {
    printf("%s -> %d\n", (*it).first.c_str(), (*it).second);
  }
  printf("token map:\n");
  for (TokenMap::const_iterator it = tokenmap.begin(); it != tokenmap.end(); ++it) {
    printf("%d -> %s\n", (*it).first, (*it).second.c_str());
  }
}

//------------------------------------------------------------------------------
